package com.tqz.juc.atomic;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.UnaryOperator;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2022/2/6 18:01
 */
public class AtomicReferenceFieldUpdaterTest {
    
    static AtomicReferenceFieldUpdater<User, String> updater = AtomicReferenceFieldUpdater.newUpdater(User.class,
            String.class, "name");
    
    public static void main(String[] args) {
        User user = new User(1, "zs");
        
        // 第一种方式修改
        System.out.println(updater.get(user));
        updater.getAndSet(user, "ls");
        System.out.println(updater.get(user));
        
        // 第二种方式修改
        UnaryOperator<String> unaryOperator = s -> {
            return "ww";
        };
        System.out.println(updater.updateAndGet(user, unaryOperator));
    }
    
    static class User {
        
        int id;
        
        volatile String name;
        
        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
    
}
